package com.atguigu.springcloud.Controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.lb.Loadbalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.xml.ws.Service;
import java.net.URI;
import java.util.List;

@RestController
public class OrderController {
    //public static final String PAYMENT_URL = "http://localhost:8003/payment/get/3";
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    public static final String PAYMENT_URL1 = "http://localhost:8003/payment/creat";
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private Loadbalancer loadBalanced;
    @Resource
    private RestTemplate restTemplate;
    @GetMapping("/consumer/payment/create")
    public String create(Payment payment){
        return   restTemplate.postForObject(PAYMENT_URL1,payment,String.class);
    }
    @GetMapping("/consumer/payment/get/{id}")
    public String getPayment(@PathVariable("id") int id){
        System.out.println(PAYMENT_URL);
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/3",String.class);
    }
    @GetMapping(value = "/consumer/payment/lb")
    public String getPaymentLB(){
        List<ServiceInstance> instances=discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances==null || instances.size()<=0){
            return null;
        }
        ServiceInstance serviceInstance=loadBalanced.instances(instances);
        URI uri=serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/payment/lb",String.class);
    }
}
